const WXAPI = require('apifm-wxapi')
const TOOLS = require('../../utils/tools.js')
const AUTH = require('../../utils/auth')
const CONFIG = require('../../config.js')
const APP = getApp()

Page({
  data: {
    xyd: [],
    collect01: [],
    collect02: [],
    collect03: [],
    wdsjh: wx.getStorageSync("wdsjh") ? wx.getStorageSync("wdsjh") : '',
    qj: wx.getStorageSync("qj") ? wx.getStorageSync("qj") : 'bz',
    zdydh: wx.getStorageSync("zdydh") ? wx.getStorageSync("zdydh") : '',
    zdylogo: wx.getStorageSync("zdylogo") ? wx.getStorageSync("zdylogo") : '',

    dh_tap_index: 4,
    tel: wx.getStorageSync("tel") ? wx.getStorageSync("tel") : '',
    menuList: [],
    // 下拉菜单的选项数组
    array: wx.getStorageSync("qj") == 'hz' || wx.getStorageSync("qj") == 'bz' ? ['服务', '收藏'] : ['Service', 'Collect'],
    // 选中的索引，默认选中第一个（索引为 0）
    selectedIndex: 0,
    menuList: [[{ name: '预约', nameEn: 'Appointment', id: 'a01' }, { name: '项目', nameEn: 'Project', id: 'a02' }, { name: '客服', nameEn: 'CustomerService', id: 'a03' }, { name: '落地', nameEn: 'Landing', id: 'a04' }, { name: '售后', nameEn: 'AfterSales', id: 'a05' }], [{ name: '案例', nameEn: 'Case', id: 'a01' }, { name: '项目', nameEn: 'Project', id: 'a02' }, { name: '产品', nameEn: 'Product', id: 'a03' }]],
    caseIndex: 0,
    showPop: false,
    caseIndexName0: '',
    caseIndexName1: '',
    caseIndexName2: '',
    caseIndexName3: '',
    caseIndexName4: '',
    caseIndexName5: '',
    articleList: [], // 文章列表数据
    page: 1,         // 当前页码（初始为第1页）
    pageSize: 10,    // 每页条数
    isLoading: false, // 是否正在加载
    noMoreData: false, // 是否已加载全部
    k: '',
    yy: [],
    info: '',
    nodeStyle: {
      'h3': 'margin:30px 0;'
    },
    wishFoldersID: "",
    fxlx: 1,
    wishFolders: []

  },
  onLoad: function (e) {
    // this.cmsPage();
    // this.loadArticles();
    this.commentList();

    WXAPI.jsonDeleteV2({
      token: wx.getStorageSync('token'),
      id: 400398822
    })
  },
  shareItems(e) {
    let that = this;
    let index = e.currentTarget.dataset.index;
    let item = that.data.xyd[index];
    wx.showShareMenu({
      withShareTicket: true,
      menus: ['shareAppMessage', 'shareTimeline']
    })
  },

  showItems(e) {
    let that = this;
    let index = e.currentTarget.dataset.index;
    console.log("xx", e);

    wx.navigateTo({
      url: '/packageYt/my/xyd?id=' + that.data.wishFoldersID + '&index=' + index,
    })
  },
  getPhoneNumber(e) {
    console.log(e.detail.code)  // 动态令牌
    console.log(e.detail.errMsg) // 回调信息（成功失败都会返回）
    console.log(e.detail.errno)  // 错误码（失败时返回）
    let that = this;
    WXAPI.bindMobileWxaV2(wx.getStorageSync('token'), e.detail.code,
    ).then(res => {
      if (res.code == 0) {
        wx.showToast({
          title: that.data.qj == 'hz' || that.data.qj == 'bz' ? '绑定成功' : 'Bind Success',
          icon: 'success',
        })
        that.setData({
          wdsjh: res.data,
        })
        wx.setStorageSync('wdsjh', res.data)
        that.getxmList();
      } else {
        wx.showToast({
          title: that.data.qj == 'hz' || that.data.qj == 'bz' ? '绑定失败' : 'Bind Failed',
          icon: 'none',
        })
      }
    })
  },



  async commentList() {
    let that = this;
    const res = await WXAPI.commentListV2({
      token: wx.getStorageSync('token'),
      type: 5,
      uid: wx.getStorageSync('uid'),
    })
    if (res.code == 0) {
      let temp = res.data.result;
      // console.log("yy111", temp);
      temp.map(element => {
        element.content = element.content.split(',')
        element.extJson = {
          类型: element.content[1],
          需求: element.content[2],
          电话: element.content[0],
          项目地址: element.content[3],
          预约门店: element.content[4],
          预约门店id: element.content[5],
        }
      });

      that.setData({
        yy: temp
      })
      console.log("yy", that.data.yy);
    } else {
      that.setData({
        yy: []
      })
    }
    that.loadWishFolders();
  },

  // 加载心愿单文件夹
  loadWishFolders() {
    // 调用JSON接口获取文件夹列表
    WXAPI.jsonListV3({
      token: wx.getStorageSync('token'),
      type: "wish_folder",
      page: 1,
      pageSize: 100
    }).then(res => {
      if (res.code === 0) {

        console.log("wishFolders", res);


        this.setData({ wishFolders: res.data.result[0].content.data || [], wishFoldersID: res.data.result[0].id });
        console.log("wishFolders", this.data.wishFolders, this.data.wishFoldersID);
      }
    });
  },

  // 选择心愿单文件夹
  // selectFolder(e) {
  //   console.log("e", e.currentTarget.dataset);
  //   let index = e.currentTarget.dataset.index;
  //   this.setData({
  //     dh_tap_index: index,
  //   })
  // },


  cancel_reservation(e) {
    console.log("e", e.currentTarget.dataset);
    let id = e.currentTarget.dataset.id;
    // 提示确定要取消吗
    let that = this;
    wx.showModal({
      title: that.data.qj == 'hz' || that.data.qj == 'bz' ? '提示' : 'Tip',
      content: that.data.qj == 'hz' || that.data.qj == 'bz' ? '确定要取消吗？' : 'Are you sure you want to cancel?',
      success: function (res) {
        if (res.confirm) {
          if (id) {
            WXAPI.cancelReservation({
              token: wx.getStorageSync('token'),
              id: id,
            }).then(res => {
              if (res.code == 0) {
                wx.showToast({
                  title: that.data.qj == 'hz' || that.data.qj == 'bz' ? '取消成功' : 'Cancel Success',
                  icon: 'success',
                })
                that.commentList();
              } else {
                wx.showToast({
                  title: that.data.qj == 'hz' || that.data.qj == 'bz' ? '取消失败' : 'Cancel Failed',
                  icon: 'none',
                })
              }
            })
          }


        }
      }
    })

  },

  openCustomerService(e) {
    console.log(111);

    let that = this;
    wx.openCustomerServiceChat({
      // showMessageCard: true,
      // sendMessageTitle: that.data.xx.info.name,
      // sendMessagePath: '/packageYt/ting/detail?id=' + that.data.xx.info.id,
      // sendMessageImg: that.data.xx.info.logo,
      extInfo: { url: 'https://work.weixin.qq.com/kfid/kfceef083027e57f445' },
      corpId: 'wwed0dbc032bbcad61',
      success(res) {
        console.log('success', res)
      },
      fail(res) {
        console.log('fail', res)
      }
    })
  },
  navigateMYToMap(e) {
    let that = this;
    console.log("e", e.currentTarget.dataset);
    let lat = e.currentTarget.dataset.lat;
    let lng = e.currentTarget.dataset.lng;
    let name = e.currentTarget.dataset.name;
    let address = e.currentTarget.dataset.address;
    if (lat && lng) {
      wx.openLocation({
        latitude: Number(lat),
        longitude: Number(lng),
        name: name,
        address: address,
      })
    }
  },

  navigateToMap(e) {
    let that = this;
    console.log("e", e.currentTarget.dataset);
    let shopid = e.currentTarget.dataset.shopid;
    WXAPI.shopSubdetail(shopid).then(res => {
      if (res.code == 0) {
        let shop = res.data.info;
        console.log("shop", shop);
        let latitude = shop.latitude;
        let longitude = shop.longitude;
        wx.openLocation({
          latitude: Number(latitude),
          longitude: Number(longitude),
          name: shop.name,
          address: shop.address,
        })
      } else {
        wx.showToast({
          title: that.data.qj == 'hz' || that.data.qj == 'bz' ? '获取门店信息失败' : 'Get Shop Info Failed',
          icon: 'none',
        })
      }
    })
  },

  telMYClick(e) {
    let that = this;
    console.log("e", e.currentTarget.dataset);
    let tel = e.currentTarget.dataset.tel;
    wx.makePhoneCall({
      phoneNumber: tel ? tel : that.data.tel,
    })
  },

  telClick(e) {
    let that = this;
    console.log("e", e.currentTarget.dataset);
    let shopid = e.currentTarget.dataset.shopid;
    WXAPI.shopSubdetail(shopid).then(res => {
      if (res.code == 0) {
        let shop = res.data.info;
        console.log("shop", shop);
        let phone = shop.phone;
        wx.makePhoneCall({
          phoneNumber: phone ? phone : that.data.tel,
        })
      } else {
        wx.showToast({
          title: that.data.qj == 'hz' || that.data.qj == 'bz' ? '获取门店信息失败' : 'Get Shop Info Failed',
          icon: 'none',
        })
      }
    })
  },



  article_detail(e) {
    console.log("dddd", e.currentTarget.dataset);

    let id = e.currentTarget.dataset.id;
    let type = e.currentTarget.dataset.type;
    if (type == 1) {
      wx.navigateTo({
        url: '/packageYt/case/detail_kt?id=' + id,
      })
    } if (type == 2) {
      {
        wx.navigateTo({
          url: '/packageYt/case/detail_za?id=' + id,
        })
      }
    }
    if (type == 3) {
      {
        wx.navigateTo({
          url: '/packageYt/goods/detail?id=' + id,
        })
      }
    }

  },

  gobook() {
    wx.navigateTo({
      url: '/packageYt/ting/index',
    })
  },


  // 加载文章列表（核心方法）
  async loadArticles() {
    // 防止重复请求或无更多数据时继续请求
    if (this.data.isLoading || this.data.noMoreData) return;

    // 显示加载中状态
    this.setData({ isLoading: true });

    try {
      // 调用接口获取数据（传入page和pageSize）
      const res = await WXAPI.cmsArticles({
        categoryId: this.data.selectedIndex == 0 ? '200482' : '200483',
        k: this.data.k,
        page: this.data.page,
        pageSize: this.data.pageSize
      });
      console.log(res);
      // code: 700,msg: "暂无数据"
      if (res.code == 700) {
        this.setData({ noMoreData: true });
        return;
      }


      // 假设接口返回格式：{ code: 0, data: { list: [], total: 100 } }
      if (res.code == 0) {
        const newArticles = res.data.result || [];
        const oldArticles = this.data.articleList;
        const total = res.data.totalRow || 0; // 总条数

        // 拼接新数据
        this.setData({
          articleList: oldArticles.concat(newArticles),
          page: this.data.page + 1, // 页码+1，下次加载下一页
        });

        // 判断是否已加载全部（当前列表长度 >= 总条数）
        if (this.data.articleList.length >= total) {
          this.setData({ noMoreData: true });
        }
      }
    } catch (err) {
      console.error('加载失败：', err);
      wx.showToast({ title: '加载失败', icon: 'none' });
    } finally {
      // 无论成功失败，都关闭加载中状态
      this.setData({ isLoading: false });
    }
  },

  // 滚动到底部触发加载下一页
  onScrollToBottom() {
    this.loadArticles();
  },


  case_nav(e) {
    let temp = e.currentTarget.dataset.index;
    this.setData({
      caseIndex: temp,
    })
    if (this.data.selectedIndex == 0) {
      if (temp == 0) {
        this.commentList();
      }
      if (temp == 1 || temp == 3) {
        if (this.data.wdsjh) {
          this.getxmList();
        }
      }
      if (temp == 4) {
        this.cmsPage('yt0001');
      }
    }

    if (this.data.selectedIndex == 1) {
      if (temp == 0) {
        this.loadcase(1);
      }
      if (temp == 1) {

        this.loadcase(2);

      }
      if (temp == 2) {

        this.loadcase(3);

      }
    }

  },

  async getxmList() {
    let that = this;

    const res = await WXAPI.cmsArticles({
      categoryId: '200485',
      keywordsLike: this.data.wdsjh,
      page: 1,
      pageSize: 100
    });
    console.log(res);
    // code: 700,msg: "暂无数据"
    if (res.code == 0) {
      let temp = [];
      // 通过文字id获取详情
      for (let i = 0; i < res.data.result.length; i++) {
        const element = res.data.result[i];
        let detail = await WXAPI.cmsArticleDetail(element.id);
        console.log(detail);
        if (detail.code == 0) {
          // element.content = detail.data.info.content;
          temp.push(detail.data);
        }
      }
      console.log("ddd", temp);

      that.setData({
        xm: temp
      });

    } else {
      that.setData({
        xm: []
      });

    }


  },




  async cmsPage(e) {
    const res = await WXAPI.cmsPage(e)

    let info = res.data.info.content;
    info = info.replace(/\<img/g, "<img style='max-width: 100%;width:auto;height:auto;margin:10px 0;float:left;display:block '")

    info = info.replace(/\<h3/g, "<h3 style='margin:20px 0;'")
    info = info.replace(/\<h2/g, "<h2 style='margin:20px 0;'")
    info = info.replace(/\<h4/g, "<h4 style='margin:20px 0;'")
    info = info.replace(/\<ul/g, "<ul style='margin:20px 0;'")
    info = info.replace(/\<ol/g, "<ol style='margin:20px 0;'")


    console.log("ccc", info);

    this.setData({
      // xx: res.data,
      info: info
    })


  },

  // 下拉选项改变时的回调函数
  bindPickerChange: function (e) {
    console.log('选中的索引为', e.detail.value);
    // 更新选中的索引
    this.setData({
      selectedIndex: e.detail.value,
      caseIndex: 0
    });

    // 可在这里根据选中的选项执行相应的逻辑，比如切换展示不同的内容
    if (e.detail.value == 0) {
      this.commentList();
      // 选中“图库”时的逻辑
      console.log('选择了服务');
    } else if (e.detail.value == 1) {
      // 重置页码为第1页
      this.setData({
        collect01: [],
        collect02: [],
        collect03: [],
      });
      this.loadcase(1);

      // 选中“整案”时的逻辑
      console.log('选择了收藏');
    }
  },


  loadcase(e) {
    let type = '';
    if (e == 1) {
      type = "gallery";
    }
    if (e == 2) {
      type = "case";
    }
    if (e == 3) {
      type = "goods";
    }
    // 调用JSON接口获取文件夹列表
    WXAPI.jsonListV3({
      token: wx.getStorageSync('token'),
      type: type,
      page: 1,
      pageSize: 100
    }).then(res => {
      if (res.code === 0) {
        if (res.data.result.length > 0) {
          if (e == 1) {
            this.setData({ collect01: res.data.result[0].content.data || [] });
          }
          if (e == 2) {
            this.setData({ collect02: res.data.result[0].content.data || [] });
          }
          if (e == 3) {
            this.setData({ collect03: res.data.result[0].content.data || [] });
          }

          console.log("collect03", this.data.collect03);


        }

      }
    });
  },

  loadcase2() {
    // 调用JSON接口获取文件夹列表
    WXAPI.jsonListV3({
      token: wx.getStorageSync('token'),
      type: "case",
      page: 1,
      pageSize: 100
    }).then(res => {
      if (res.code === 0) {
        this.setData({ caseList: res.data.result[0].content.data || [], caseListID: res.data.result[0].id || '' });
      }
    });
  },

  loadcase3() {
    // 调用JSON接口获取文件夹列表
    WXAPI.jsonListV3({
      token: wx.getStorageSync('token'),
      type: "goods",
      page: 1,
      pageSize: 100
    }).then(res => {
      if (res.code === 0) {
        this.setData({ caseList: res.data.result[0].content.data || [], caseListID: res.data.result[0].id || '' });
      }
    });
  },

  zdy_top_nav() {
    wx.navigateTo({
      url: '/pages/xl/index',
    })
  },
  dh_tap(e) {
    //console.log(e);
    let temp = e.currentTarget.dataset.id;
    this.setData({
      dh_tap_index: temp
    })
    if (temp == 0) {
      wx.reLaunch({
        url: '/packageYt/index/index',
      })
    }
    if (temp == 1) {
      wx.reLaunch({
        url: '/packageYt/case/index',
      })
    }
    if (temp == 2) {
      wx.reLaunch({
        url: '/packageYt/ting/index',
      })
    }
    if (temp == 3) {
      wx.reLaunch({
        url: '/packageYt/goods/index',
      })
    }
    if (temp == 4) {
      wx.reLaunch({
        url: '/packageYt/my/index',
      })
    }
  },


  onShow: function (e) {
    this.setData({
      qj: wx.getStorageSync("qj") ? wx.getStorageSync("qj") : 'bz'
    })

  },

  async getGoodsList(categoryId, append) {
    if (categoryId == 0) {
      categoryId = "";
    }
    wx.showLoading({
      title: ''
    })
    // https://www.yuque.com/apifm/nu0f75/wg5t98
    const res = await WXAPI.goodsv2({
      categoryId: categoryId,
      page: this.data.curPage,
      pageSize: this.data.pageSize
    })
    wx.hideLoading()
    if (res.code == 404 || res.code == 700) {
      let newData = {
        loadingMoreHidden: false
      }
      if (!append) {
        newData.goods = []
      }
      this.setData(newData);
      return
    }
    let goods = [];
    if (append) {
      goods = this.data.goods
    }
    for (var i = 0; i < res.data.result.length; i++) {
      const item = res.data.result[i]
      const hidden_goods_index = wx.getStorageSync('hidden_goods_index')
      if (hidden_goods_index.indexOf(item.id) != -1) {
        continue
      }
      goods.push(item);
    }
    this.setData({
      loadingMoreHidden: true,
      goods: goods,
    });
  },

  onShareAppMessage: function () {
    return {
      title: '"' + wx.getStorageSync('mallName') + '" ' + wx.getStorageSync('share_profile'),
      // path: '/pages/index/index?inviter_id=' + wx.getStorageSync('uid')
    }
  },
  onShareTimeline() {
    return {
      title: '"' + wx.getStorageSync('mallName') + '" ' + wx.getStorageSync('share_profile'),
      // query: 'inviter_id=' + wx.getStorageSync('uid'),
      // imageUrl: wx.getStorageSync('share_pic')
    }
  },

  // onReachBottom: function () {

  // },
  // onPullDownRefresh: function () {

  // }
})